import { defineStore } from 'pinia'
import { store } from '../index'
import { getAccessToken, removeToken } from '@/utils/auth'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import type { UserInfoVO, UserType } from '@/api/login/types'
import { getInfoApi, loginOutApi } from '@/api/login'

export interface UserState {
  userKey: string
  userInfo: UserInfoVO
  isSetUser: boolean
}

export const useUserStore = defineStore('admin-user', {
  state: (): UserState => ({
    userKey: CACHE_KEY.USER_CACHE, // 登录信息存储字段-建议每个项目换一个字段，避免与其他项目冲突 hooks/web/useCache CACHE_KEY 更换
    userInfo: {
      permissions: [],
      roles: [],
      user: {
        avatar: '',
        id: 0,
        nickname: ''
      }
    },
    isSetUser: false
  }),
  getters: {
    getUserKey(): string {
      return this.userKey
    },
    getIsSetUser(): boolean {
      return this.isSetUser
    },
    getPermissions(): string[] {
      return this.userInfo.permissions
    },
    getRoles(): string[] {
      return this.userInfo.roles
    },
    getUser(): UserType {
      return this.userInfo.user
    }
  },
  actions: {
    async setUserInfoAction() {
      if (!getAccessToken()) {
        this.resetState
        return null
      }
      const { wsCache } = useCache()
      let userInfo = wsCache.get(CACHE_KEY.USER_CACHE)
      if (!userInfo) {
        userInfo = await getInfoApi()
      }
      if (userInfo) {
        this.isSetUser = true
        wsCache.set(CACHE_KEY.USER_CACHE, userInfo, { exp: 1 * 60 * 60 })
      }
    },
    async loginOut() {
      await loginOutApi()
      removeToken()
      this.resetState()
    },
    resetState() {
      this.userInfo.permissions = []
      this.userInfo.roles = []
      this.isSetUser = false
      this.userInfo.user = {
        id: 0,
        avatar: '',
        nickname: ''
      }
    }
  }
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
